//
//  LTLEmoticonCell.m
//  WeiBo
//
//  Created by LiTaiLiang on 16/11/14.
//  Copyright © 2016年 LTL. All rights reserved.
//

#import "LTLEmoticonCell.h"
#import "LTLemoticonButton.h"

@implementation LTLEmoticonCell
#pragma mark - 设置数据
- (void)setArryr:(NSArray<LTLEmotion *> *)arryr
{
    _arryr = arryr;
   
    //隐藏子控件
    for (UIView *v in self.contentView.subviews) {
        v.hidden = YES;
    }
    ///打开删除按钮
    self.contentView.subviews.lastObject.hidden = NO;
    //遍历数组赋值
    
    [_arryr enumerateObjectsUsingBlock:^(LTLEmotion * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LTLemoticonButton *btn = self.contentView.subviews[idx];
         btn.emoticon = obj;
        
    }];
    
}

#pragma mark - 构造函数
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        
    }
    return self;
}
#pragma mark - 设置界面
- (void)prepareUI {
    //行
    NSInteger rowCount = 3;
    //列
    NSInteger colCount = 7;
    //左边距
    CGFloat leftMargin = 8;
    //下边距
    CGFloat bottomMargin = 16;
    
    CGFloat w = ceil((self.bounds.size.width - 2 * leftMargin) / colCount);
    CGFloat h = ceil((self.bounds.size.height - bottomMargin) / rowCount);
    
    ///布局
    for (NSInteger i = 0; i < 21; i++) {
        NSInteger col = i % colCount;
        NSInteger row = i / colCount;
        CGRect rect = CGRectMake(col * w + leftMargin, row * h, w, h);
        
        UIButton *button = [LTLemoticonButton emoticonButtonWithFrame:rect tag:i];
        
        [self.contentView addSubview:button];
        
        [button addTarget:self
                   action:@selector(clickEmoticonButton:)
         forControlEvents:UIControlEventTouchUpInside];
    }
    
     //设置删除按钮
    ((LTLemoticonButton *)self.contentView.subviews.lastObject).deleteButton = YES;
    
    
}
//点击事件
- (void)clickEmoticonButton:(LTLemoticonButton *)button {
   
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    dic[@"LTLemoticonButton"] = button;
    
    ///发送输入通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LTLemoticonButton" object:nil userInfo:[dic copy]];
    
}
///布局
-(void)layoutSubviews
{
    [super layoutSubviews];
    //行
    NSInteger rowCount = 3;
    //列
    NSInteger colCount = 7;
    //左边距
    CGFloat leftMargin = 8;
    //下边距
    CGFloat bottomMargin = 16;
    
    CGFloat w = ceil((self.bounds.size.width - 2 * leftMargin) / colCount);
    CGFloat h = ceil((self.bounds.size.height - bottomMargin) / rowCount);
    //遍历子控件设置位置
    [self.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger col = idx % colCount;
        NSInteger row = idx / colCount;
        CGRect rect = CGRectMake(col * w + leftMargin, row * h, w, h);
        
        obj.frame = rect;
        
    }];

}
@end
